package com.example.lemieripetizioni;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Iscrizione extends Activity implements OnClickListener {

	Context ctx = null;
	EditText nome;
	EditText cognome;
	private String path;
	EditText professione;
	EditText dataNascita;
	Button buttonLoadImage;
	Button OpenPDF;
	private String TAG = "Iscrizione";

	static final int DATE_DIALOG_ID = 0;
	private static int RESULT_LOAD_IMAGE = 1;
	private static int RESULT_LOAD_CV = 2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.iscrizione);

		ctx = this.getApplicationContext();

		buttonLoadImage = (Button) findViewById(R.id.btnCaricaImmagine);
		buttonLoadImage.setOnClickListener(this);

		OpenPDF = (Button) findViewById(R.id.selezionaIlCV);
		OpenPDF.setOnClickListener(this);

		dataNascita = (EditText) findViewById(R.id.vl_data_nascita_iscrizione);
		dataNascita.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (v == dataNascita)
					showDialog(DATE_DIALOG_ID);
				return false;
			}
		});

	}

	// quando viene selezionata un'immagine dalla gallery
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			ImageView imageView = (ImageView) findViewById(R.id.imgView);

			try {
				loadImage(picturePath, imageView);
				path = picturePath;
			} catch (FileNotFoundException e) {
				Log.e(TAG, "errore durante l'apertura del file");
				e.printStackTrace();
				throw new RuntimeException();
			} catch (IOException e) {
				Log.e(TAG, "errore durante l'apertura del file");
				e.printStackTrace();
			}

		}
		
		if (requestCode == RESULT_LOAD_CV && resultCode == RESULT_OK && null != data) {
			Uri selectedImage = data.getData();
			selectedImage.getPath();

		}
	}

	// metodo privato per la gestione dell'immagine caricata dalla gallery
	private void loadImage(String picturePath, ImageView imageView) throws FileNotFoundException, IOException {
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		FileInputStream fis;
		fis = new FileInputStream(picturePath);
		BitmapFactory.decodeStream(fis, null, o);
		fis.close();
		final int REQUIRED_SIZE = 70;
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
				break;
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}
		BitmapFactory.Options op = new BitmapFactory.Options();
		op.inSampleSize = scale;
		fis = new FileInputStream(picturePath);
		Bitmap bitmap = BitmapFactory.decodeStream(fis, null, op);
		fis.close();

		imageView.setImageBitmap(bitmap);
	}

	// viene aperto il dialog con del picker
	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance();
		int cyear = c.get(Calendar.YEAR);
		int cmonth = c.get(Calendar.MONTH);
		int cday = c.get(Calendar.DAY_OF_MONTH);
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
		}
		return null;
	}

	// quando viene confermata la data valido_da del dataPicker
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		// onDateSet method
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			String date_selected = String.valueOf(dayOfMonth) + "/"
					+ String.format("%2s", String.valueOf(monthOfYear + 1)).replace(' ', '0') + "/" + String.valueOf(year);
			// Toast.makeText(getApplicationContext(),
			// "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
			dataNascita.setText(date_selected);
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.form_button:

			nome = (EditText) findViewById(R.id.vl_nome_iscrizione);
			cognome = (EditText) findViewById(R.id.vl_cognome_iscrizione);
			professione = (EditText) findViewById(R.id.vl_professione_iscrizione);
			dataNascita = (EditText) findViewById(R.id.vl_data_nascita_iscrizione);

			break;

		case R.id.btnCaricaImmagine:
			Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

			startActivityForResult(i, RESULT_LOAD_IMAGE);
			break;
		case R.id.selezionaIlCV:
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		    intent.setType("file/*");
            
            startActivityForResult(intent, RESULT_LOAD_CV);
			break;
		}
	}
}
